#!/usr/bin/env python2
#coding=UTF-8
#page_drawer_pillow.py

from __future__ import division
import os.path

#import math
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
from PIL import ImageColor
from pymodules.little_functions import *



_info = '''
  本模块是专门用来根据输入的名单列表生成页面大图的。
  与page_drawer的区别是使用了pillow库来处理图像，希望会比imagemagick好些。
  只包括Draw_cast_page()一个函数，它的参数：
  lines是已经格式化好的二维列表 settings是全局设置变量 filename是输出图片的文件名。
  '''
  
class Cast_list_page:
  def __init__(self,settings,castlines=None) :
    self.STYLE_DICT={
      'TITLE' : self.Draw_TITLE,
      'COMPANY' : self.Draw_COMPANY,
      'NAMES' : self.Draw_NAMES,
      'JOBANDNAME' : self.Draw_JOBANDNAME,
      'LOGO' : self.Draw_LOGO,
      'ERRORTEXT' : self.Draw_ERRORTEXT
      }
    self.Update_settings(settings)
    if castlines != None :
      self.Get_lines(castlines)
    
    
    
  #接收名单列表
  def Get_lines(self, lines) :
    self._castlines=lines
    self._pageheight = self.Calc_page_height(self._castlines)
    self.page_image=Image.new('RGB', (self._pagewidth,self._pageheight), self._backcolor)
    
  #读取默认设置
  def Update_settings(self, settings) :
    self._vheight=settings['VIDEO_HEIGHT']    #视频高度
    self._pagewidth=settings['VIDEO_WIDTH']    #页面宽度
    self._textsize = settings['TEXT_BASE_SIZE']    #基本字号
    self._linespace = settings['LINE_BASE_SPACE']    #基本行间距
    self._textFontfile = os.path.join(settings['FONT_DIR'] , settings['FONT'])
    
    
    self._textFont = ImageFont.truetype(self._textFontfile,self._textsize)    #生成普通字体类
    
    #标题属性
    self._titlesize = self._textsize + 10
    self._titleprespace = self._linespace * 4
    self._titlepostpace = self._linespace * 3
    self._titleFont = ImageFont.truetype(self._textFontfile, self._titlesize)    #生成TITLE字体类
    
    #职务和人名间距
    self._jobandnamedeltax = int(settings['JOB_NAME_SPACE'] * self._textsize / 2)
    
    #单行人名属性
    self._namesspace = ' ' * int(2 * settings['NAMES_SPACE'])
    
    #公司名属性
    self._companysize = self._textsize + 5
    #self._companyspace = self._linespace * 2
    self._companyFont = ImageFont.truetype(self._textFontfile, self._companysize)     #生成COMPANY字体类
    
    #背景和字体颜色
    self._backcolor=ImageColor.getcolor('black' , 'RGB')
    self._textcolor=ImageColor.getcolor('white', 'RGB')
    
    #公司logo属性
    self._logodir = settings['LOGO_DIR']   #logo读取目录
    self._logomaxsquare = (self._textsize * 6) ** 2
  
  #计算页面长度函数
  def Calc_page_height(self, flines):
    pagey=self._vheight*2
    for fline in flines:
      if fline[0] == 'TITLE':
        y = self._titleFont.getsize(fline[1])[1]
        pagey += ( y + self._titleprespace + self._titlepostpace)
      elif fline[0] == 'JOBANDNAME' :
        temp=' '
        text=temp.join(fline[1])
        y = self._textFont.getsize(text)[1]
        pagey += ( y + self._linespace )
      elif fline[0] == 'NAMES':
        y = self._textFont.getsize(fline[1][0])[1]
        pagey += ( y + self._linespace )
      elif fline[0] == 'COMPANY':
        y = self._companyFont.getsize(fline[1])[1]
        pagey += ( y + self._linespace )
      elif fline[0] == 'LOGO':
        logo=Image.open(os.path.join(self._logodir,fline[1]))
        y = self.Calc_logo_size(logo)[1]
        pagey += (y + self._linespace *2)
    return pagey
    
  #计算logo大小函数,输入已经打开的Image类
  def Calc_logo_size(self, img):
    logox,logoy = img.size
    logosquare = logox * logoy
    logoaspect = logox / logoy
    if logosquare > self._logomaxsquare :
      newy = int(( self._logomaxsquare / logoaspect)**0.5)
      newx = int(self._logomaxsquare / newy)
      return (newx,newy)
    else:
      return (logox,logoy)
    
  #绘制标题
  def Draw_TITLE(self, x,y,line,img):
    textwidth=self._titleFont.getsize(line)[0]
    real_x = int(x - textwidth / 2)
    xy = (real_x , y)
    
    drawline=ImageDraw.Draw(img)
    drawline.text(xy, line, fill=self._textcolor, font=self._titleFont)

  
  #绘制职务和人名
  def Draw_JOBANDNAME(self, x,y,line,img):
    job,name = line
    jobwidth = self._textFont.getsize(job)[0]
    jobx = x - self._jobandnamedeltax - jobwidth
    namex = x + self._jobandnamedeltax
    
    jobxy=(jobx,y)
    namexy=(namex,y)
    
    drawline=ImageDraw.Draw(img)
    drawline.text(jobxy, job, fill=self._textcolor, font=self._textFont)
    drawline.text(namexy, name, fill=self._textcolor, font=self._textFont)
  
  #绘制公司名
  def Draw_COMPANY(self, x, y, line, img):
    textwidth=self._companyFont.getsize(line)[0]
    real_x = int(x - textwidth / 2)
    xy = (real_x , y)
    
    drawline=ImageDraw.Draw(img)
    drawline.text(xy, line, fill=self._textcolor, font=self._companyFont)
    
  #绘制单行名字列表
  def Draw_NAMES(self, x, y, line, img):
    nameslist=line
    text = self._namesspace.join(nameslist)
    textwidth=self._textFont.getsize(text)[0]
    real_x = int(x - textwidth / 2)
    xy = (real_x , y)
    
    drawline=ImageDraw.Draw(img)
    drawline.text(xy, text, fill=self._textcolor, font=self._textFont)
    
  #绘制logo  
  def Draw_LOGO(self, x,y,line,img):
    logofile=os.path.join(self._logodir.encode('UTF-8'), line.encode('UTF-8'))
    logoimg=Image.open(logofile)
    logowidth, logoheight=self.Calc_logo_size(logoimg)
    logosize = (logowidth,logoheight)
    realx = int(x-(logowidth/2))
    xy = (realx,y)
    newlogo=logoimg.resize(logosize)
    img.paste(newlogo,xy)
    return logoheight
    
  #无法识别的文本
  def Draw_ERRORTEXT(self, x, y, line, img):
    text = u'无法识别的文本:' + line
    textwidth=self._textFont.getsize(text)[0]
    real_x = int(x - textwidth / 2)
    xy = (real_x , y)
    drawline=ImageDraw.Draw(img)
    drawline.text(xy, text, fill=ImageColor.getcolor('red','RGB'), font=self._textFont)
    


  #绘制
  def Draw_page(self):
    linex = self._pagewidth / 2    #x坐标始终对齐在中间
    liney = self._vheight    #开始之前先空一屏
    for line in self._castlines:
      style=line[0]
      text=line[1]
      ##如果是标题
      if style=='TITLE': 
        liney += self._titleprespace
        self.STYLE_DICT.get(style)(linex,liney,text,self.page_image)
        liney += (self._titlepostpace + self._titlesize)
      elif style == 'LOGO':
        liney += self._linespace
        picheight=self.STYLE_DICT.get(style)(linex,liney,text,self.page_image)
        liney += (picheight + self._linespace)
      else:
        self.STYLE_DICT.get(style)(linex,liney,text,self.page_image)
        liney += ( self._linespace + self._textsize ) 

  def Save(self, filename) :
    #name,ext = filename.split('.')
    #self.page_image.save(name,ext)
    self.page_image.save(filename)
  
  

if __name__ == '__main__' :
  print( _info)
